package com.heima.news.utils;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 敏感词工具类
 * 功能：从Nacos加载敏感词配置，提供敏感词检查功能
 */
@Component
public class SensitiveWordUtil {

    @Autowired
    private NacosConfigManager nacosConfigManager;

    // 存储敏感词的集合
    private static Set<String> sensitiveWords = new HashSet<>();

    /**
     * 初始化方法，在 Bean 创建后自动调用
     * 加载初始敏感词配置，并注册监听器实现热更新
     */
    @PostConstruct
    public void init() {
        String dataId = "sensitive-word-config.properties";
        String group = "DEFAULT_GROUP";

        try {
            // 从 Nacos 获取初始配置
            String config = nacosConfigManager.getConfigService().getConfig(dataId, group, 5000);
            updateSensitiveWords(config);

            // 注册监听器，实现配置热更新
            nacosConfigManager.getConfigService().addListener(dataId, group, new AbstractListener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    updateSensitiveWords(configInfo);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException("Nacos加载敏感字失败", e);
        }
    }

    /**
     * 更新敏感词列表
     */
    private void updateSensitiveWords(String configInfo) {
        if (configInfo != null && configInfo.contains("sensitive.words=")) {
            // 提取敏感词部分并分割成列表
            String wordsStr = configInfo.split("sensitive.words=")[1].trim();
            List<String> words = Arrays.asList(wordsStr.split(","));
            sensitiveWords.clear();
            sensitiveWords.addAll(words);
        }
    }

    /**
     *检查指定文本是否包含敏感词。text：待检查的文本。如果包含敏感词返回 true，否则返回 false
     */
    public static boolean containsSensitiveWord(String text) {
        for (String word : sensitiveWords) {
            if (text != null && text.contains(word.trim())) {
                return true;
            }
        }
        return false;
    }
}
